package com.dlg.commons.spring.fix.http;

import java.io.IOException;
import java.util.Collection;

import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.annotation.Immutable;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;

/**
 * Request interceptor that adds default request headers.
 *
 * @since 4.0
 */
@SuppressWarnings("deprecation")
@Immutable
public class FixRequestDefaultHeaders implements HttpRequestInterceptor {

	private final Collection<? extends Header> defaultHeaders;

	/**
	 * @since 4.3
	 */
	public FixRequestDefaultHeaders(final Collection<? extends Header> defaultHeaders) {
		super();
		this.defaultHeaders = defaultHeaders;
	}

	public FixRequestDefaultHeaders() {
		this(null);
	}

	public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
		Args.notNull(request, "HTTP request");

		final String method = request.getRequestLine().getMethod();
		if (method.equalsIgnoreCase("CONNECT")) {
			return;
		}

		// Add default headers
		@SuppressWarnings("unchecked")
		Collection<? extends Header> defHeaders = (Collection<? extends Header>) request.getParams().getParameter(ClientPNames.DEFAULT_HEADERS);
		if (defHeaders == null) {
			defHeaders = this.defaultHeaders;
		}

		if (defHeaders != null) {
			for (final Header defHeader : defHeaders) {
				if (!request.containsHeader(defHeader.getName())) {
					request.addHeader(defHeader);
				}
			}
		}
	}

}
